import torch.nn as nn
from torch.nn import init
import torch.utils.data
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt

mnist_train = torchvision.datasets.MNIST(root='./Datasets/MNIST', train=True, download=True, transform=transforms.ToTensor())
mnist_test = torchvision.datasets.MNIST(root='./Datasets/MNIST', train=False, download=True, transform=transforms.ToTensor())

batch_size = 200
train_iter = torch.utils.data.DataLoader(mnist_train, batch_size=batch_size, shuffle=True, num_workers=0)
test_iter = torch.utils.data.DataLoader(mnist_test, batch_size=batch_size, shuffle=False,num_workers=0)

a, b =[], []
for x, y in mnist_train:
    a.append(x)
    b.append(y)

x = torch.stack(a, dim=0)
y = torch.tensor(b)

num_inputs, num_outputs, num_hiddens = 784, 10, 256



def evaluate_accuracy(test_iter, net):
    acc_sum, n = 0, 0
    for X, y in test_iter:
        y_hat = net(X)
        acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
        n += y.shape[0]
    return acc_sum / n

num_epochs = 12

def train(x_train, y_train, x_valid, y_valid, num_epochs, batch_size):
    train_ls, test_ls, x_epoch, list_train_acc, list_test_acc = [], [], [], [], []
    train_dataset = torch.utils.data.TensorDataset(x_train,y_train)
    train_dataiter = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=0)
    valid_dataset = torch.utils.data.TensorDataset(x_valid,y_valid)
    valid_dataiter = torch.utils.data.DataLoader(dataset=valid_dataset, batch_size=batch_size, shuffle=False, num_workers=0)

    class FlattenLayer(nn.Module):
        def __init__(self):
            super(FlattenLayer, self).__init__()

        def forward(self, x):
            return x.view(x.shape[0], -1)

    net = nn.Sequential(
        FlattenLayer(),
        nn.Linear(num_inputs, num_hiddens),
        nn.ReLU(),  
        nn.Linear(num_hiddens, num_outputs),
    )

    for params in net.parameters():
        init.normal_(params, mean=0, std=0.1)

    loss = torch.nn.CrossEntropyLoss()
    optimizer = torch.optim.SGD(net.parameters(), lr=0.2)

    for epoch in range(num_epochs):
        train_1_sum, train_acc_sum, n = 0.0, 0.0, 0
        train_1_test_sum, n_test = 0.0, 0
        for X, y in train_dataiter:
            y_hat = net(X)
            l = loss(y_hat, y).sum()
            optimizer.zero_grad()
            l.backward()
            optimizer.step()

            train_1_sum += l.item()
            train_acc_sum += (y_hat.argmax(dim=1) == y).sum().item()
            n += y.shape[0]
        train_ls.append(train_1_sum / n)
        x_epoch.append(epoch + 1)
        test_acc = evaluate_accuracy(test_iter, net)
        list_train_acc.append(train_acc_sum / n)
        list_test_acc.append(test_acc)
        # print('epoch %d, loss %.4f, train acc %.3f, test acc %.3f' % (epoch + 1, train_1_sum / n, train_acc_sum / n, test_acc))

        for X_test, y_test in valid_dataiter:
            y_hat = net(X_test)
            l = loss(y_hat, y_test).sum()
            train_1_test_sum += l.item()
            n_test += y_test.shape[0]
        test_ls.append(train_1_test_sum / n_test)

    return train_ls, test_ls, list_train_acc, list_test_acc


def get_k_fold_data(k, i, X, y):
    # 返回第i折交叉验证时所需要的训练和验证数据，分开放，X_train为训练数据，X_valid为验证数据
    assert k > 1
    fold_size = X.shape[0] // k  
    X_train, y_train = None, None
    for j in range(k):
        idx = slice(j * fold_size, (j + 1) * fold_size)  #slice(start,end,step)切片函数
        X_part, y_part = X[idx, :], y[idx]
        if j == i:
            X_valid, y_valid = X_part, y_part
        elif X_train is None:
            X_train, y_train = X_part, y_part
        else:
            X_train = torch.cat((X_train, X_part), dim=0)
            y_train = torch.cat((y_train, y_part), dim=0)
    return X_train, y_train, X_valid, y_valid

def k_fold(k, X_train, y_train, num_epochs, batch_size):
    for i in range(k):
        data = get_k_fold_data(k, i, X_train, y_train) # 获取k折交叉验证的训练和验证数据
        train_ls, valid_ls, train_acc, valid_acc = train(*data, num_epochs, batch_size)
        train_l_sum, valid_l_sum, train_acc_sum, valid_acc_sum = 0.0, 0.0, 0.0, 0.0
        for ii in train_ls:
            train_l_sum += ii
        for jj in valid_ls:
            valid_l_sum += jj
        for ii in train_acc:
            train_acc_sum += ii
        for jj in valid_acc:
            valid_acc_sum += jj

        print('fold %d, train loss %.4f, valid loss %.4f, train acc %.4f, test acc %.4f' % (i + 1, train_l_sum / num_epochs, valid_l_sum / num_epochs, train_acc_sum / num_epochs, valid_acc_sum / num_epochs))


k_fold(10, x, y, num_epochs, batch_size)